import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { Row, Col, Card, Button, Input, Modal, message, Drawer, Icon, Layout, Spin, Select, Menu, Dropdown, Tag, } from "antd";
import { searchFile, knowledgeListFile, docLibraryInfo, docLibraryList, docLibraryAuth, docLibraryListAdmin } from "@/services/knowledgeFile";
import styles from "./index.less";
import UserSession from "@/UserSession";
import { getAuthority } from "@/utils/judgeAuthority";
const LeftTree = React.lazy(() => import("./leftTree/index"));
const FileList = React.lazy(() => import("./fileList/index"));
const { Header, Content, Footer, Sider } = Layout;

import { routerRedux } from "dva/router";
import { FsSvg } from "@/utils/CommonComponent";

class OverView extends Component {
	constructor(props) {
		super(props);
		this.state = {
			globalLoading: true,
			code: "",
			tableLoading: true,
			nodeId: "",
			nodeIdName: "所有分类",
			nodePath: "",
			parentId: "0",
			isShard: false,
			query: {
				current: 1,
				size: 10,
				title: '',
				categoryId: '',
				docType: '',
				docStatus: '',
				status: '',
			},
			total: 0,
			list: [],
      libraryInfo:{},
      libraryList:[],
      authInfo:{},
      dropDownSearch:false,
      dropDownVisible:false,
      dropDownSearchVal:"",
      isAdmin:false
		};
	}

	componentDidMount() {
		this.checkImport()
    this.getLibraryInfo()
    this.getLibraryList()
    this.getLibraryAuth()
    this.setState({
      isAdmin:this.props.location.pathname.indexOf("publicResource") != -1
    })
	}

	checkImport = async () => {
		this.isShowGlobalLoading(false)
		setTimeout(() => {
			if (this.LeftTree) {
				this.LeftTree.fetch(true)
			}
		}, 300)
	}

	// ----树形图方法开始----
	terrNodeId = (nodeId, nodeIdName, nodePath, isShard, parentId) => {
		let { query } = this.state;
		query.current = 1;
		query.size = 10;
		query.categoryId = nodeId === "" ? `${currentUser.robotId}-root` : nodeId;
		this.setState({ nodeId, nodeIdName, nodePath, isShard, parentId, query }, () => {
			this.fetchFileList();
		});
	};

	// 停用启用变更需要刷新列表
	refresh = (code) => {
		this.setState({ code });
	};
	// ----树形图方法结束----

	fetchFileList() {
		// console.log(this.state);

		const { query, nodeId } = this.state;
		const { dispatch, match: { params: { id }, }, currentUser } = this.props;
		let object = { ...query };
		this.setState({ tableLoading: true }, async () => {
			// object.size = query.limit;
			// object.current = query.page;
			object.categoryId = nodeId === "" ? `${currentUser.robotId}-root` : nodeId;
			// object.categoryParentPath = parentPath;
			object.isHeadquarters = UserSession.isSystemKnowledge();
			if (UserSession.isSystemKnowledge()) {
				let res = await knowledgeListFile(object);
				this.setState({
					list: res.records,
					total: res.total,
					searchObj: object,
					loading: false,
					tableLoading: false,
					qaIdList: [],
					classId: "",
					selectedRowKeys: [],
				});
			} else {
				let res = await searchFile(object)
				this.setState({
					list: res.records,
					total: res.total,
					searchObj: object,
					loading: false,
					tableLoading: false,
					qaIdList: [],
					classId: "",
					selectedRowKeys: [],
				});
			}
		});
	};
	fetchGraphListByPage = (page, limit, values) => {
		let { query } = this.state;
		query.current = page;
		query.size = limit;
		query.title = values?.key;
		query.docType = values?.queryType;
		query.docStatus = values?.qaType;
		query.status = values?.status;
		this.setState({ tableLoading: true, query }, () => {
			this.fetchFileList();
		})
	};

	isShowGlobalLoading = (globalLoading) => {
		this.setState({ globalLoading });
	};

	cancelImport = async () => {
		this.isShowGlobalLoading(false)
	}

	componentWillUnmount() {
		console.log('离开了当前页面');
	}

  getLibraryList = async () => {
    const { dropDownSearchVal,isAdmin } = this.state;
    let res = {}
    if(isAdmin){
      res = await docLibraryListAdmin({current:1,size:999999999,search:dropDownSearchVal})
    }else{
      res = await docLibraryList({current:1,size:999999999,search:dropDownSearchVal,type:0})
    }
     
    this.setState({
      libraryList:res.records
    })
  }

  getLibraryInfo = async () => {
    const { match: { params: { id }, }, route, location: { params } } = this.props;
    const res = await docLibraryInfo({id})
    this.setState({
      libraryInfo:res
    })
  }

  handleMenuClick = e => {
    const {  history } = this.props;
    const { libraryInfo,isAdmin } = this.state;
    let pathname = ''
    switch(e.key){
      case 'home':
        pathname = isAdmin ? "/publicResource/documentLibrary" : "/documentLibrary"
        history.push({ pathname });
        break;
      case 'search':
        this.setState({dropDownSearch:true})
        break;
      default :
        if(e.key == libraryInfo.id){
          return false
        }
        pathname = isAdmin ? "/publicResource/documentLibrary/" + e.key + "/file" : "/documentLibrary/" + e.key + "/file"
        history.push({ pathname });
        this.checkImport()
        this.onVisibleChange(false)
        setTimeout(() => {
          this.getLibraryInfo()
        },100)
        break;
    }
		
  }

  getLibraryAuth = async () => {
    const { match: { params: { id }, }, route, location: { params } } = this.props;
    const res = await docLibraryAuth({libraryId:id})
    this.setState({
      authInfo:res
    })
  }

  changeDropDownSearch = e => {
    this.setState({dropDownSearchVal:e.target.value},() => {
      this.getLibraryList()
    })
  }

  onVisibleChange = visible => {
    if(!visible){
      this.setState({
        dropDownSearch:false,
        dropDownSearchVal:""
      },() => {
        this.getLibraryList()
      })
    }
    this.setState({
      dropDownVisible:visible
    })
  }

	render() {
		const { match: { params: { id }, }, route, location: { params } ,history} = this.props;
		const { list, total, query, globalLoading, tableLoading,libraryInfo,libraryList,authInfo,dropDownSearch,dropDownSearchVal,dropDownVisible,isAdmin } = this.state;
    
    const menu = (
      <Menu onClick={this.handleMenuClick} style={{minWidth:"302px",maxHeight:'70vh',overflowY:"auto"}}>
        <Menu.Item key='home'>
          <FsSvg type='home' />
          <span>主页</span>
        </Menu.Item>
        <Menu.Divider disabled style={{width:"calc(100% - 24px)",margin:"4px auto"}} />
        <Menu.Item key='search' className="library-search" style={{marginBottom:4}}>
          {
            dropDownSearch ?(
              <Input 
                prefix={<FsSvg type='search' style={{margin:0}} />} 
                onChange={e => this.changeDropDownSearch(e)}
                value={dropDownSearchVal}
              />
            ) : (
              <span style={{fontSize:12,color:"#646a73"}}>文档库</span>
            )
          }
          {
            dropDownSearch ? '': (
              <FsSvg type='search' />
            )
          }
        </Menu.Item>
        {
          libraryList.map(item => {
            return (
              <Menu.Item key={item.id} style={{justifyContent:"space-between",padding:'5px 12px'}}>
                <span style={{display:"flex",alignItems:"center"}}>
                  <FsSvg type='library' style={{marginRight:"14px",marginLeft:0}} />
                  <span style={{color:libraryInfo.id == item.id ? '#1456f0' : ''}}>{item.name}</span>
                  { libraryInfo.permissionType == 1 ? <span className={styles.nameTag}>公开</span> : '' }
                </span>
                {
                  libraryInfo.id == item.id ? <FsSvg type='check' /> : ''
                }
                
              </Menu.Item>
            )
          })
        }
      </Menu>
    );

		return (
			<Suspense fallback={<PageLoading />}>
				<Layout style={{ minHeight: '100%' }}>
					<Sider width={260} style={{ background: "#ffffff",padding:10,height: 'calc(100vh - 85px)',overflowY:"auto" }} className={styles.siderTree}>
            <Dropdown overlay={menu} trigger={['click']} visible={dropDownVisible} overlayClassName='knowledgeFileDropDown' onVisibleChange={this.onVisibleChange}>
              <div className={dropDownVisible ? `${styles.libraryBox} ${styles.libraryBoxCheck}` : `${styles.libraryBox}`}>
                <span className={styles.nameBox}>
                  <span className={styles.name}>{libraryInfo.name}</span>
                  { libraryInfo.permissionType == 1 ? <span className={styles.nameTag}>公开</span> : '' }
                </span>
                <Icon type="caret-down" />
              </div>
            </Dropdown>
            <LeftTree
              terrNodeId={this.terrNodeId}
              authority={getAuthority(route.authority)}
              onRef={(ref) => (this.LeftTree = ref)}
              getListByTreeRoot={data => this.terrNodeId(data.id, data.title, data.path, false, data.parentId, null)}
              categoryId={id}
              location={this.props.location}
              authInfo={authInfo}
              isAdmin={isAdmin}
            />
					</Sider>
					<Content style={{ borderLeft: "1px solid #E6ECF6", background: '#ffffff' }}>
            <Card bordered={false} bodyStyle={{ paddingTop: 10, paddingBottom: 6 }}>
              <FileList
                fileCategoryId={this.state.nodeId}
                fileCategoryName={this.state.nodeIdName}
                fileCategoryPath={this.state.nodePath}
                fileCategoryParentId={this.state.parentId}
                tabPaneList={this.leftTreeList}
                list={list}
                total={total}
                current={query.current}
                graphLoading={tableLoading}
                fetchGraphListByPage={this.fetchGraphListByPage}
                pathId={id}
                authority={getAuthority(route.authority)}
                onRef={(ref) => (this.FileListCom = ref)}
                history={history}
                authInfo={authInfo}
                isAdmin={isAdmin}
              />
            </Card>
					</Content>
				</Layout>
				{/* </Spin> */}
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(OverView);
